//===========================================================
//					es_spr
//
//	Работа со спрайтами
//===========================================================

#include "es_spr.h"

// Спрайтовый менеджер
cSpriteManager *SpriteManager;
// SDL поверхность
SDL_Surface*    Surf_Display;

//----------------------------- SpriteManager -----------------------------
// Конструктор
cSpriteManager::cSpriteManager() 
{
}

// Деструктор
cSpriteManager::~cSpriteManager()
{
	for ( int i = 0;i < sprites.size();i++ )
		SDL_FreeSurface(sprites[i].image);
}

//Загрузка спрайта
bool cSpriteManager::LoadSprite(char *path)
{
	stSprite Sprite_return;
	SDL_Surface* Surf_Temp = NULL;

    if ( (Surf_Temp = IMG_Load(path)) == NULL )
	{
		LogWrite(" !!!ERROR!!! - Can't load sprite %s", path);
        return false;
	}

    Sprite_return.image = SDL_DisplayFormatAlpha(Surf_Temp);
	Sprite_return.name = getFileName(path);
    SDL_FreeSurface(Surf_Temp);

	sprites.push_back(Sprite_return);

    return true;
}

// Отрисовка
void cSpriteManager::DrawSprite(string spritename, int x, int y, int x2, int y2, int w, int h) 
{
    SDL_Rect DestR;
    DestR.x = x;
    DestR.y = y;

	if ( w == 0 )
		SDL_BlitSurface(getSpriteByName(spritename).image, NULL, Surf_Display, &DestR);
	else
	{
		 SDL_Rect SrcR;

		 SrcR.x = x2;
		 SrcR.y = y2;
		 SrcR.w = w;
		 SrcR.h = h;

		 SDL_BlitSurface(getSpriteByName(spritename).image, &SrcR, Surf_Display, &DestR);
	}
}

// Получение спрайта по его имени
stSprite cSpriteManager::getSpriteByName(string name)
{
	for ( int i = 0;i < sprites.size();i++ )
		if ( sprites[i].name == name )
			return sprites[i];
	LogWrite(" !!!ERROR!!! - Cannot find sprite '%s'in Spritemanager", name.c_str());
}